<?php

namespace common\biz;

use peng\enums\DBOperator;

/**
 * 车辆
 *
 * @author peng.huang
 */
class CarsBiz extends \common\base\BaseBiz {

    /**
     * 构造函数
     */
    public function __construct() {
        $this->dao = static::getDao('common\dao\CarsDao');
    }

    /**
     * 查询数据
     * 
     * @param string $fields [字段]
     * @param object $entity [实体对象]
     * @param boolean $checkUserToken [验证账号和令牌]
     * @return array
     */
    public function find($fields, $entity, $checkUserToken = FALSE) {
        if (!$entity->validate()) {
            return FALSE;
        }

        // 验证账号和令牌
        if ($checkUserToken && !$this->isUserTokenValid($entity)) {
            return FALSE;
        }

        return $this->dao->findAll($fields, array('userid' => $entity->userid, 'status' => 0), ' id desc');
    }

    /**
     * 保存数据
     * 
     * @param object $entity [实体对象]
     * @param boolean $checkUserToken [验证账号和令牌]
     * @return bool
     */
    public function save($entity, $checkUserToken = FALSE) {
        if (!$entity->validate()) {
            return FALSE;
        }

        // 验证账号和令牌
        if ($checkUserToken && !$this->isUserTokenValid($entity)) {
            return FALSE;
        }

        $result = -1;
        switch ($entity->operator) {
            case DBOperator::INSERT: // 新增
            case DBOperator::UPDATE: // 修改     
                $data = $this->getSavedData($entity);
                $result = $this->dao->save($data);
                break;
            case DBOperator::DELETE: // 逻辑删除
                $result = $this->dao->update(array('status' => 1), array('id' => $entity->id, 'userid' => $entity->userid));
                break;
        }

        return -1 < $result;
    }

}
